css2<- read.csv("css11_cv.csv")
css2$part<- css2$cash + css2$vouchers
css2$part[css2$part==2]<-1
css2$part<- css2$part*100
css2$income<- as.numeric(substr(css2$income,2,length(css2$income)))
css2$income_perc<- ceiling(ecdf(css2$income)(css2$income)*10)
css2$voucher_yr<-0
css2$voucher_yr[css2$elec_year>2015]<-1
css2$elec_year<- css2$elec_year-2011

block_groups<- unique(css2$bg_ct19)

#mean inc dec of donor 
ww<-length(block_groups)*6
empty_df2<- data.frame(1:ww)
empty_df2$block_group<-NA
empty_df2$year<-NA
empty_df2$tempc<-NA

q<- length(block_groups)

for (i in 1:q) {
  curr_bg<- block_groups[i]
  curr_df<- subset(css2, css2$bg_ct19==curr_bg)
  yrs<- c(0,2,4,6,8,10)
  for (j in 1:6) {
    curr_yr<- yrs[j]  
    curr_df2<- subset(curr_df, curr_df$elec_year==curr_yr)
    curr_df2<- curr_df2[complete.cases(curr_df2$income),]
    curr_df2<- subset(curr_df2, curr_df2$part==100)
    curr_temp<- mean(curr_df2$income_perc, na.rm=T)
    
    curr_row<- (i-1)*6 + j
    empty_df2$block_group[curr_row]<- curr_bg
    empty_df2$year[curr_row]<- curr_yr
    empty_df2$tempc[curr_row]<- curr_temp
  }
}

empty_df2$voucher_yr<- 0
empty_df2$voucher_yr[empty_df2$year>4]<- 1



#mean inc  of donor 
empty_df3<- data.frame(1:ww)
empty_df3$block_group<-NA
empty_df3$year<-NA
empty_df3$tempc<-NA

for (i in 1:q) {
  curr_bg<- block_groups[i]
  curr_df<- subset(css2, css2$bg_ct19==curr_bg)
  yrs<- c(0,2,4,6,8,10)
  for (j in 1:6) {
    curr_yr<- yrs[j]  
    curr_df2<- subset(curr_df, curr_df$elec_year==curr_yr)
    curr_df2<- curr_df2[complete.cases(curr_df2$income),]
    curr_df2<- subset(curr_df2, curr_df2$part==100)
    curr_temp<- mean(curr_df2$income, na.rm=T)
    
    curr_row<- (i-1)*6 + j
    empty_df3$block_group[curr_row]<- curr_bg
    empty_df3$year[curr_row]<- curr_yr
    empty_df3$tempc[curr_row]<- curr_temp
  }}

empty_df3$voucher_yr<- 0
empty_df3$voucher_yr[empty_df3$year>4]<- 1


names(empty_df3)<- c( "X1.ww", "block_group", "year",    "mean_don_inc", "voucher_yr")
names(empty_df2)<- c( "X1.ww", "block_group", "year",    "mean_don_inc_dec", "voucher_yr")
bg_df<- full_join(empty_df2, empty_df3) 


xx_meaninc2<- felm(mean_don_inc_dec~voucher_yr+year|as.factor(block_group)|0|0, data=bg_df)
xx_meaninc1<- felm(mean_don_inc_dec~voucher_yr*year|as.factor(block_group)|0|0, data=bg_df)
xx_meanincdec1<- felm(mean_don_inc~voucher_yr *year |as.factor(block_group)|0|0, data=bg_df)
xx_meanincdec2<- felm(mean_don_inc~voucher_yr +year |as.factor(block_group)|0|0, data=bg_df)
summary(xx_meaninc1, robust=T)
summary(xx_meaninc2, robust=T)
summary(xx_meanincdec1, robust=T)
summary(xx_meanincdec2, robust=T)
stargazer(xx_meaninc2,xx_meaninc1,xx_meanincdec2,xx_meanincdec1)
